<template>
  <div class="add-enterprise">
    <header class="add-header">
      <div class="left">
        <span class="arrow" @click="$router.back()"><i class="el-icon-arrow-left" />返回</span>
        <span>|</span>
        <span>{{ id ? '编辑企业' : '添加企业' }}</span>
      </div>
      <div class="right">
        黑马程序员
      </div>
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form ref="ruleFormRef" label-width="100px" :model="addForm" :rules="rules">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
              <el-select v-model="addForm.industryCode">
                <el-option
                  v-for="item in industryList"
                  :key="item.industryCode"
                  :label="item.industryName"
                  :value="item.industryCode"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <el-form-item label="营业执照">
              <el-upload action="#" :file-list="fileList" :http-request="uploadRequest" :before-upload="beforeUpload">
                <!-- :before-upload="beforeUpload" 禁止上传 -->
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过 5MB</div>
              </el-upload>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button>重置</el-button>
        <el-button type="primary" @click="confirmAdd">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { getIndustryListAPI, addEnterpriseAPI, uploadLicenseAPI, getEnterpriseInfoAPI, updateEnterpriseAPI } from '@/api/enterprise'
export default {
  data() {
    return {
      addForm: {
        name: '', // 企业名称
        legalPerson: '', // 法人
        registeredAddress: '', // 注册地址
        industryCode: '', // 所在行业
        contact: '', // 企业联系人
        contactNumber: '', // 联系人电话
        businessLicenseUrl: '', // 营业执照url
        businessLicenseId: '' // 营业执照id
      },
      industryList: [],
      fileList: [],
      rules: {
        name: [
          { required: true, message: '请输入企业名称', trigger: 'blur' }
        ],
        legalPerson: [
          { required: true, message: '请输入法人', trigger: 'blur' }
        ],
        registeredAddress: [
          { required: true, message: '请输入注册地址', trigger: 'blur' }
        ],
        industryCode: [
          { required: true, message: '请选择行业', trigger: 'blur' }
        ],
        contact: [
          { required: true, message: '请输入企业联系人', trigger: 'blur' }
        ],
        contactNumber: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[34578]\d{9}$/, message: '请输入正确格式手机号' }
        ],
        businessLicenseUrl: [
          { required: true, message: '请上传营业执照', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    id() {
      return this.$route.query.id
    }
  },
  created() {
    this.getIndustryList()
    if (this.id) {
      this.getEnterpriseInfo()
    }
  },
  methods: {
    async confirmAdd() {
      this.$refs.ruleFormRef.validate((valid) => {
        if (valid) {
          // 调用接口
          if (this.id) {
            console.log(this.addForm)
            // 编辑
            updateEnterpriseAPI({
              name: this.addForm.name, // 企业名称
              legalPerson: this.addForm.legalPerson, // 法人
              registeredAddress: this.addForm.registeredAddress, // 注册地址
              industryCode: this.addForm.industryCode, // 所在行业
              contact: this.addForm.contact, // 企业联系人
              contactNumber: this.addForm.contactNumber, // 联系人电话
              businessLicenseUrl: this.addForm.businessLicenseUrl, // 营业执照url
              businessLicenseId: this.addForm.businessLicenseId, // 营业执照id
              id: this.$route.query.id // id
            }).then(() => {
              this.$message.success('更新成功')
              // 返回列表页
              this.$router.back()
            }).catch((error) => {
              this.$message.error('更新失败：' + error.message)
            })
          } else {
            addEnterpriseAPI(this.addForm).then(() => {
              this.$message.success('添加成功')
              // 返回列表页
              this.$router.back()
            }).catch((error) => {
              this.$message.error('添加失败：' + error.message)
            })
          }
        } else {
          this.$message.error('请完善表单信息')
        }
      })
    },
    async getIndustryList() {
      const res = await getIndustryListAPI()
      console.log(res.data)
      this.industryList = res.data
    },
    async uploadRequest(data) {
      // 从传入的数据中获取文件对象
      const file = data.file
      // 创建一个 FormData 对象，用于存储要上传的文件及其他信息
      const formData = new FormData()

      try {
        // 将文件添加到 FormData 中，键名为 'file'
        formData.append('file', file)

        // 同时添加一个额外的信息 'type'，其值为 'businessLicense'
        formData.append('type', 'businessLicense')

        // 调用 uploadAPI 函数并传入 formData 进行文件上传，使用 await 等待请求完成
        const res = await uploadLicenseAPI(formData)

        // 将服务器返回结果中的 id 赋值给组件的 addForm.businessLicenseId 属性
        this.addForm.businessLicenseId = res.data.id

        // 将服务器返回结果中的 url 赋值给组件的 addForm.businessLicenseUrl 属性
        this.addForm.businessLicenseUrl = res.data.url

        // 将文件信息添加到组件的 fileList 数组中，用于在 el-upload 组件中显示已上传文件列表
        // el-upload 组件要求列表对象必须包含 name 和 url 属性
        this.fileList.push({
          name: file.name,
          url: res.data.url
        })
      } catch (error) {
        console.error('Error in uploadRequest:', error)
        this.$message.error('文件上传失败：' + error.message)
      }
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 5MB!')
      }
      return isJPG || isPNG && isLt5M
    },
    async getEnterpriseInfo() {
      const res = await getEnterpriseInfoAPI(this.id)
      this.addForm = res.data
    }
  }
}
</script>

<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
